#!/usr/bin/env python3
"""
钉钉智能助手系统启动脚本
"""

import os
import sys
import logging
from pathlib import Path

# 设置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler("system.log")
    ]
)
logger = logging.getLogger("SystemStartup")

def check_environment():
    """检查环境配置"""
    logger.info("检查环境配置...")
    
    required_env_vars = [
        'OPENAI_API_KEY',
        'MYSQL_HOST',
        'MYSQL_USER', 
        'MYSQL_PASSWORD',
        'MYSQL_DATABASE',
        'MILVUS_HOST',
        'REDIS_HOST'
    ]
    
    missing_vars = []
    for var in required_env_vars:
        if not os.getenv(var):
            missing_vars.append(var)
    
    if missing_vars:
        logger.error(f"缺少环境变量: {missing_vars}")
        logger.error("请检查.env文件配置")
        return False
    
    logger.info("环境配置检查通过")
    return True

def check_dependencies():
    """检查依赖包"""
    logger.info("检查依赖包...")
    
    required_packages = [
        'langchain',
        'langgraph', 
        'openai',
        'pymilvus',
        'mysql.connector',
        'redis',
        'dingtalk_stream'
    ]
    
    missing_packages = []
    for package in required_packages:
        try:
            __import__(package.replace('-', '_').replace('.', '_'))
        except ImportError:
            missing_packages.append(package)
    
    if missing_packages:
        logger.error(f"缺少依赖包: {missing_packages}")
        logger.error("请运行: pip install -r requirements.txt")
        return False
    
    logger.info("依赖包检查通过")
    return True

def test_connections():
    """测试数据库连接"""
    logger.info("测试数据库连接...")
    
    try:
        # 测试MySQL连接
        import mysql.connector
        mysql_config = {
            'host': os.getenv('MYSQL_HOST'),
            'port': int(os.getenv('MYSQL_PORT', 3306)),
            'user': os.getenv('MYSQL_USER'),
            'password': os.getenv('MYSQL_PASSWORD'),
            'database': os.getenv('MYSQL_DATABASE')
        }
        conn = mysql.connector.connect(**mysql_config)
        conn.close()
        logger.info("MySQL连接测试通过")
        
    except Exception as e:
        logger.error(f"MySQL连接失败: {e}")
        return False
    
    try:
        # 测试Redis连接
        import redis
        redis_client = redis.Redis(
            host=os.getenv('REDIS_HOST'),
            port=int(os.getenv('REDIS_PORT', 6380)),
            password=os.getenv('REDIS_PASSWORD'),
            decode_responses=True
        )
        redis_client.ping()
        logger.info("Redis连接测试通过")
        
    except Exception as e:
        logger.error(f"Redis连接失败: {e}")
        return False
    
    try:
        # 测试Milvus连接
        from pymilvus import connections
        connections.connect(
            alias="default",
            host=os.getenv('MILVUS_HOST'),
            port=int(os.getenv('MILVUS_PORT', 19530))
        )
        logger.info("Milvus连接测试通过")
        
    except Exception as e:
        logger.error(f"Milvus连接失败: {e}")
        return False
    
    return True

def start_webhook_service():
    """启动钉钉Webhook服务"""
    logger.info("启动钉钉Webhook服务...")
    
    try:
        from dingding.DingWebHook import main
        main()
    except KeyboardInterrupt:
        logger.info("服务已停止")
    except Exception as e:
        logger.error(f"服务启动失败: {e}")
        raise

def start_interactive_mode():
    """启动交互模式"""
    logger.info("启动交互模式...")
    
    try:
        from dingding.Agents import AgentClass
        
        print("\n🚀 钉钉智能助手系统")
        print("=" * 50)
        print("系统已启动，您可以开始对话了！")
        print("输入 'quit' 或 'exit' 退出系统")
        print("=" * 50)
        
        agent = AgentClass()
        
        while True:
            try:
                user_input = input("\n用户: ").strip()
                
                if user_input.lower() in ['quit', 'exit', '退出']:
                    print("再见！")
                    break
                
                if not user_input:
                    continue
                
                print("助手: 正在处理您的请求...")
                result = agent.run_agent(user_input, "interactive_user")
                
                if result.get('success', False):
                    print(f"助手: {result.get('output', '抱歉，没有获得回复')}")
                else:
                    print(f"助手: 抱歉，处理请求时出现错误：{result.get('error', '未知错误')}")
                    
            except KeyboardInterrupt:
                print("\n\n再见！")
                break
            except Exception as e:
                print(f"助手: 抱歉，出现了错误：{e}")
                
    except Exception as e:
        logger.error(f"交互模式启动失败: {e}")
        raise

def main():
    """主函数"""
    print("🚀 钉钉智能助手系统启动器")
    print("=" * 50)
    
    # 加载环境变量
    from dotenv import load_dotenv
    load_dotenv()
    
    # 检查环境
    if not check_environment():
        sys.exit(1)
    
    if not check_dependencies():
        sys.exit(1)
    
    if not test_connections():
        sys.exit(1)
    
    # 选择启动模式
    print("\n请选择启动模式:")
    print("1. 钉钉Webhook服务模式")
    print("2. 交互式对话模式")
    
    while True:
        choice = input("\n请输入选择 (1/2): ").strip()
        
        if choice == '1':
            start_webhook_service()
            break
        elif choice == '2':
            start_interactive_mode()
            break
        else:
            print("无效选择，请输入 1 或 2")

if __name__ == "__main__":
    main()
